package com.imu.utils;

import com.imu.common.utils.SpringContextUtils;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;
import org.springframework.data.redis.core.RedisTemplate;

public class RedisLockUtil {
    private static final Log log = LogFactory.get(RedisLockUtil.class);
    //缺省过期的时间 默认为秒
    private static  final int defaultExpire = 60;

    /**
     * 加锁
     * @param key redis key
     * @param expire 过期时间，单位秒
     * @return true:加锁成功，false，加锁失败
     */
    public static boolean lock(String key, int expire) {
        expire = expire == 0 ? defaultExpire : expire;
        RedisTemplate<String,String> redisTemplate = SpringContextUtils.getBean("redisTemplate",RedisTemplate.class);

        long value = System.currentTimeMillis() + expire * 1000;
        boolean status = redisTemplate.opsForValue().setIfAbsent(key, String.valueOf(value));

        if(status) {
            return true;
        }
        try {
            long oldExpireTime = Long.parseLong(redisTemplate.opsForValue().get(key));
            if (oldExpireTime < System.currentTimeMillis()) {
                long newExpireTime = System.currentTimeMillis() + expire * 1000;
                long currentExpireTime = Long.parseLong(redisTemplate.opsForValue().getAndSet(key, String.valueOf(newExpireTime)));
                if (currentExpireTime == oldExpireTime) {
                    return true;
                }
            }
            return false;
        }catch(Exception e){
            log.error(e);
            return lock(key,expire);
        }
    }

    /**
     * 解锁
     * @param key
     */
    public static void unLock(String key) {
        RedisTemplate<String,String> redisTemplate = SpringContextUtils.getBean("redisTemplate",RedisTemplate.class);
        redisTemplate.delete(key);
    }
}
